package com.farm.farming.service.impl;

import com.farm.entity.PageResult;
import com.farm.farming.dao.Cust_permissionMapper;
import com.farm.farming.pojo.Cust_permission;
import com.farm.farming.service.Cust_perimssionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class Cust_perimssionServiceImpl implements Cust_perimssionService {

    @Autowired
    private Cust_permissionMapper cust_permissionMapper;

    @Override
    public int add(Cust_permission cust_permission) {
        Cust_permission permission = cust_permissionMapper.save(cust_permission);

        return 0;
    }

    @Override
    public int delete(Integer id) {
        //先查询角色和权限的中间表
        int count = cust_permissionMapper.selectTrolePermissionByPermissionId(id);
        if (count!=0){
            throw  new RuntimeException("修改权限失败");
        }

        //没有数据再删除permission
        cust_permissionMapper.deleteById(id);
        return 0;
    }

    @Override
    public int update(Cust_permission cust_permission) {

        Cust_permission save = cust_permissionMapper.save(cust_permission);

        return 0;
    }

    @Override
    public List<Cust_permission> findAll() {
        return null;
    }

    @Override
    public PageResult<Cust_permission> findPage(Cust_permission cust_permission,Integer currentPage,Integer size) {
        //分页条件
        PageRequest pageRequest = PageRequest.of(currentPage, size);
        //查询条件
        if (cust_permission==null){
            cust_permission = new Cust_permission();
        }
        Example<Cust_permission> example = Example.of(cust_permission, ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()));

        Page<Cust_permission> all = cust_permissionMapper.findAll(example, pageRequest);

        return new PageResult<>(all.getTotalElements(),all.getContent());
    }

    @Override
    public Cust_permission findById(Integer id) {
        return cust_permissionMapper.getOne(id);
    }
}
